package com.lizemin.filter;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author lzm
 * @date 2025/3/31 20:37
 * @description 添加日志打印的过滤器
 */
@WebFilter("/*")
@Slf4j
public class LogFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("进入了过滤器");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 替换原始请求对象和响应对象，用于缓存请求体和响应体
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

        // 放行请求，放行后，会调用其他过滤器的filter方法以及接口方法
        filterChain.doFilter(requestWrapper, responseWrapper);

        // 执行完接口方法后才会执行下面的代码
        byte[] reqBody = requestWrapper.getContentAsByteArray();
        String reqBodyStr = new String(reqBody, StandardCharsets.UTF_8);
        log.info("请求体中的参数为：{}", reqBodyStr);

        Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
        log.info("请求中的查询参数为：{}", JSONUtil.toJsonStr(parameterMap));

        byte[] respBody = responseWrapper.getContentAsByteArray();
        String respBodyStr = new String(respBody, StandardCharsets.UTF_8);
        log.info("本次请求返回的响应为：{}", respBodyStr);
        responseWrapper.copyBodyToResponse();
        log.info("放行后的日志....");
    }


}
